952. Largest Component Size by Common Factor - LeetCode Solution


Math

Python Code:

class Solution:
    def largestComponentSize(self, A: List[int]) -> int:
        pri = []
        for x in range(2, int(max(A)**0.5)+1):
            for y in pri:
                if x % y == 0:
                    break
            else:
                pri.append(x)
    
        factors = collections.defaultdict(list)         # compute factors of each 'a'
        for a in A:
            x = a
            for p in pri:
                if p*p > x:
                    break
                if x % p == 0:
                    factors[a].append(p)
                    while x % p == 0:
                        x //= p
            if x > 1:                                   # a new prime found
                factors[a].append(x)
                pri.append(x)
                
        pri = list(set(pri))
        n = len(pri)
        p2i = {p: i for i,p in enumerate(pri)}       # prime to index
        
        parent = [i for i in range(n)]                  # union-find on primes
        
        def find(i):
            if i != parent[i]:
                parent[i] = find(parent[i])
            return parent[i]
        
        def union(i,j):
            pi, pj = find(i), find(j)
            if pi != pj:
                parent[pi] = pj

        for a in A:
            if factors[a]:
                p0 = factors[a][0]
                for p in factors[a][1:]:                # link two primes if they are factors of 'a'
                    union(p2i[p0], p2i[p])
        
        count = collections.Counter(find(p2i[factors[a][0]]) for a in A if factors[a])      # each 'a' corresponds to a prime index
        return max(count.values())
        


Comments

Submit
0 Comments
More Questions

265A - Colorful Stones (Simplified Edition)
296A - Yaroslav and Permutations
967B - Watering System
152A - Marks
1398A - Bad Triangle
137A - Postcards and photos
1674D - A-B-C Sort
334A - Candy Bags
855A - Tom Riddle's Diary
1417A - Copy-paste
1038A - Equality
1061A - Coins
1676E - Eating Queries
1447A - Add Candies
1721D - Maximum AND
363C - Fixing Typos
1401A - Distance and Axis
658A - Bear and Reverse Radewoosh
1721E - Prefix Function Queries
977E - Cyclic Components
1140D - Minimum Triangulation
75C - Modified GCD
1722A - Spell Check
1722B - Colourblindness
1722D - Line
1722C - Word Game
1722G - Even-Odd XOR
552E - Vanya and Brackets
933A - A Twisty Movement
1722F - L-shapes